package com.moshang.blog.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moshang.blog.core.constant.CurrentUser;
import com.moshang.blog.entity.SysDept;
import com.moshang.blog.core.constant.MySysUser;
import com.moshang.blog.mapper.DeptMapper;
import com.moshang.blog.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xww
 * Created on 2019/7/2.
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper,SysDept> implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    /**
     * 查找所有的部门的树形结构
     */
    public List<SysDept> selectAllDeptTree() {
        QueryWrapper<SysDept> param = new QueryWrapper<>();
        param.eq("parent_id",0);
        param.eq("is_activited",0);
        param.orderBy(true,true,"sort ");
        return deptMapper.selectList(param);
    }
    /**
     * 获取所有菜单并添加一个根节点 (树形结构)
     */
    @Override
    public List<SysDept> selectAllDeptTreeAndRoot() {
        List<SysDept> deptList = selectAllDeptTree();
        SysDept root = new SysDept();
        root.setId(0);
        root.setDeptName("根部门");
        root.setChildren(deptList);
        List<SysDept> rootList = new ArrayList<>();
        rootList.add(root);
        return rootList;
    }

    @Override
    public List<SysDept> selectByParentId(Integer parentId) {
        QueryWrapper<SysDept> param = new QueryWrapper<>();
        param.eq("parent_id",parentId);
        param.eq("is_activited",0);
        param.orderBy(true,true,"sort");
        return deptMapper.selectList(param);
    }

    @Override
    public void swapSort(Integer currentId, Integer swapId) {
        deptMapper.swapSort(currentId,swapId);
    }

    @Override
    public void saveOrUpdateDict(SysDept sysDept) {
        CurrentUser user= MySysUser.currentUser();
        if (sysDept.getId()!=null){

            //更新操作
            sysDept.setUpdateTime(new Date());
            sysDept.setUpdateBy(user.getId());
            sysDept.setUpdateName(user.getUserName());
            deptMapper.updateById(sysDept);
        }else {
            sysDept.setCreateBy(user.getId());
            sysDept.setCreateName(user.getUserName());
            sysDept.setIsActivited(0);
            sysDept.setCreateTime(new Date());
            deptMapper.insert(sysDept);
        }
    }

    @Override
    public void deleteDept(Integer id) {
        //查询是否有子节点
        List<Integer> childIDList = deptMapper.selectChidIdById(id);
        if (childIDList.size()>0) {
            for (Integer childId : childIDList) {
                deleteDept(childId);
            }
        }
      deptMapper.deleteById(id);

    }
}
